<template>
  <el-form ref="ruleForm1Ref" :model="ruleForm1" status-icon :rules="rules_login" label-width="120px"
    class="demo-ruleForm1">
    <el-form-item label="账号" prop="phone">
      <el-input v-model.number="ruleForm1.phone" placeholder="手机号码" />
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input v-model="ruleForm1.pass" type="password" autocomplete="off" placeholder="密码" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="Login(ruleForm1Ref)">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, TabsPaneContext, FormRules } from "element-plus";
import { post } from "@/tools/api/api";
import { ElMessage } from 'element-plus'
import { debounce } from "@/hooks/tools";
import { useRouter } from 'vue-router'
import { usePhotoStore } from "@/store/photo";
const photoStore = usePhotoStore();

const router = useRouter()

const ruleForm1Ref = ref<FormInstance>();
//表单数据
const ruleForm1 = reactive({
  phone: "15555555555",
  pass: "111111",
});

//校验账号
const checkPhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("账号不能为空"));
  }
  setTimeout(() => {
    if (
      !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
        value
      )
    ) {
      callback(new Error("请输入正确的手机号码"));
    } else {
      callback();
    }
  }, 1000);
};

//登录
const Login = debounce(async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      post("userLogin", {
        password: ruleForm1.pass,
        phone: ruleForm1.phone
      }).then((res: any) => {
        if (res.code === 100) {
          localStorage.setItem('token', res.token);
          photoStore.$patch((state) => {
            state.isLogin = true;
          })
          ElMessage.success(res.msg);
          router.push('/home')
        } else ElMessage.error(res.msg)
      })
    } else {

    }
  });
});

//定义校验函数
const rules_login = reactive({
  phone: [{ validator: checkPhone, trigger: "blur" }],
});
</script>

<style lang="scss" scoped>
$item-height: 0.36rem;
$item-width: 0.6rem;
$a-font-size: 0.08rem;
$item-length:0.5rem;

form {
  padding: $item-length*0.2;

  .tips {
    color: green;
    float: right;
    font-size: 0.05rem;
  }
}
</style>
